<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by 李航.
 * Author: ls
 * Time: 2020/06/29 14:08
 * Desc: 积分商城--必须要进行登录检查
 */
class Controller_Pc_Api_Standard_Integral extends Controller_Pc_Api_Base
{
    //用户id
    private $_mid;

    //返回信息数组
    private $result = array('status'=>true, 'msg'=>'操作成功', 'data'=>array());

    public function before()
    {
        
        parent::before();
        // 检查用户是否有效
        $mid = intval($this->request_body->content->mid);
        $check_member = Model_Api_Standard_Pub::check_member_effective($mid);
        
        if($check_member['status'] == false)
        {
            $this->send_datagrams($this->client_info['id'], $check_member, $this->client_info['secret_key']);
        }

        $this->_mid = $mid;
    }

    /**
     * 获取积分商城列表页banner
     */
    public function action_get_banner()
    {
        $result = DB::select()->from('xcx_ads')->where('prefix','=','s_integral_index')
            ->order_by('displayorder','asc')->limit(10)->execute()->as_array();
        foreach($result as &$v){
            //判断产品类型
            if($v['typeid'] == 1)
            {
                $v['url'] = '/stpage/lines/pages/lineShow/lineShow';
                $mod = DB::select('litpic')->from('line');
            }
            elseif($v['typeid'] == 2)
            {
                $v['url'] = '/stpage/hotels/pages/hotelShow/hotelShow';
                $mod = DB::select('litpic')->from('hotel');
            }
            elseif($v['typeid'] == 3)
            {
                $v['url'] = '/stpage/cars/pages/carShow/carShow';
                $mod = DB::select('litpic')->from('car');
            }
            elseif($v['typeid'] == 5)
            {
                $v['url'] = '/stpage/spots/pages/mpShow/mpShow';
                $mod = DB::select('litpic')->from('spot');
            }
            elseif($v['typeid'] == 4)
            {
                $v['url'] = '/stpage/article/pages/show/show';
                $mod = DB::select('litpic')->from('article');
            }
            elseif($v['typeid'] == 8)
            {
                $v['url'] = '/stpage/visa/pages/visaDetail/visaDetail';
                $mod = DB::select('litpic')->from('visa');
            }
            elseif($v['typeid'] == 101)
            {
                $v['url'] = '/stpage/travelNotes/pages/details/details';
                $mod = DB::select('litpic')->from('travelNotes');
            }
            elseif($v['typeid'] == 104)
            {
                $v['url'] = '/stpage/ship/pages/show/show';
                $mod = DB::select('litpic')->from('ship_line');
            }
            elseif($v['typeid'] == 106)
            {
                $v['url'] = '/stpage/guide/pages/guideServiceDetail/guideServiceDetail';
                $mod = DB::select('litpic')->from('guide');
            }
            elseif($v['typeid'] == 114)
            {
                $v['url'] = '/stpage/outdoor/pages/details/details';
                $mod = DB::select('litpic')->from('outdoor');
            }
            elseif($v['typeid'] == 118)
            {
                $v['url'] = '/stpage/techan/pages/show/show';
                $mod = DB::select('litpic')->from('techan');
            }
            
            if(!empty($mod)){
               $row = $mod ->where('id','=',$v['proid'])->execute()->current();
               //增加图片绝对访问地址
               $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($row['litpic']);
            }
            $v['id'] = $v['proid'];
        }

        $this->result['data'] = $result;

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    // 会员俱乐部首页用户数据
    public function action_index()
    {
        //用户信息
        $member = Model_Member::get_member_byid($this->_mid);
        //用户等级列表
        $rank = Model_Member::member_rank($this->_mid, array('return' => 'all'));
        //会员任务
        $label = array(
            'sys_member_register' => 8,
            'sys_member_login' => 9,
            'sys_member_upload_head' => 10,
            'sys_member_bind_phone' => 11,
            'sys_member_bind_email' => 12,
            'sys_member_bind_qq' => 13,
            'sys_member_bind_sina_weibo' => 14,
            'sys_member_bind_weixin' => 15
        );

        //积分任务
        $strategy = DB::select()->from('jifen')->where(DB::expr('label in ("' . implode('","', array_keys($label)) . '")'))
            ->and_where('isopen', '=', 1)->order_by('id', 'asc')->limit(3)->execute()->as_array();
        $result = array('status'=> true, 'msg'=> '获取成功','data'=> array(
            'member'   => $member,
            'rank'   => $rank,
            'strategy'   => $strategy,
            'label'   => $label,
        ));
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //会员等级
    public function action_member_rank()
    {
        //会员信息
        $member = Model_Member::get_member_byid($this->_mid);
        //等级列表
        $grade = Model_Member::member_rank($this->_mid, array('return' => 'all'));
        foreach ($grade['grade'] as $k => &$v)
        {
            $v['rank'] = $k + 1;
        }
        if ($grade['current'] == $grade['total'])
        {
            $grade['nextGrade'] = null;
        }
        else
        {
            $nextArr = $grade['grade'][$grade['current']];
            //下一等级信息
            $grade['nextGrade'] = array('poor' => $nextArr['begin'] - $grade['jifen'], 'name' => $nextArr['name']);
        }
        if ($grade['current'] - 2 < 0)
        {
            $progress = array_slice($grade['grade'], 0, 2);
            array_unshift($progress, null);
        }
        else
        {
            $progress = array_slice($grade['grade'], $grade['current'] - 2, 3);
        }
        $result = array('status'=> true, 'msg'=> '获取成功','data'=> array(
            'grade'   => $grade,
            'progress'   => $progress,
            'member'   => $member
        ));
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //会员任务
    public function action_member_task()
    {
        //会员信息
        $member = Model_Member::get_member_byid($this->_mid);
        //会员任务
        $newer = array(
            'sys_member_register' => array('icon' => 8, 'complete' => true),
            'sys_member_upload_head' => array('icon' => 10, 'complete' => $member['litpic'] && $member['litpic'] != Model_Member::member_nopic() ? true : false, 'bind' => 'editData'),
            'sys_member_bind_phone' => array('icon' => 11, 'complete' => $member['mobile'] ? true : false, 'bind' => 'bindPhone'),
            'sys_member_bind_email' => array('icon' => 12, 'complete' => $member['email'] ? true : false, 'bind' => 'bindMailbox'),
        );
        $daily = array('sys_member_login', 'sys_write_notes', 'sys_write_jieban', 'sys_write_wenda');
        //新人任务
        $strategy = DB::select()->from('jifen')->where(DB::expr('label in ("' . implode('","', array_keys($newer)) . '")'))->and_where('isopen', '=', 1)->order_by('id', 'asc')->execute()->as_array();
        //每日任务
        $daily_strategy = DB::select()->from('jifen')->select('title', 'label', 'id', 'value')->where(DB::expr('label in("' . implode('","', $daily) . '")'))->and_where('isopen', '=', 1)->order_by('id', 'asc')->execute()->as_array();
        foreach ($daily_strategy as &$v)
        {
            if( $v['label'] == 'sys_write_wenda' ){
                $v['title'] = '提交问题';
                $v['brief'] = "成功提问一次可获赠{$v['value']}积分";
            }
            elseif( $v['label'] == 'sys_member_login' ){
                $v['title'] = '登录送积分';
                $v['brief'] = "每天登录一次获赠{$v['value']}积分";
            }
            elseif( $v['label'] == 'sys_write_notes' ){
                $v['title'] = '发布游记';
                $v['brief'] = "发表一篇可获得{$v['value']}积分";
            }
            elseif( $v['label'] == 'sys_write_jieban' ){
                $v['title'] = '发布结伴';
                $v['brief'] = "发布一次结伴可获赠{$v['value']}积分";
            }
        }
        if( St_Functions::is_normal_app_install('member_sign') && Model_Jifen::check_policy_is_open(6) ){
            $daily_strategy[] = array(
                'id' => '99997',
                'title' => '我要签到',
                'brief' => '每天签到获赠更多积分',
                'label' => 'sign',
            );
        }
        if( Model_Jifen::check_policy_is_open(1) ){
            $daily_strategy[] = array(
                'id' => '99998',
                'title' => '预订产品',
                'brief' => '成功预订产品可获赠积分',
                'label' => 'order_product',
            );
        }
        if( Model_Jifen::check_policy_is_open(2) ){
            $daily_strategy[] = array(
                'id' => '99999',
                'title' => '评论产品',
                'brief' => '成功评论可获赠积分',
                'label' => 'evaluate_product',
            );
        }
        foreach ($strategy as &$v)
        {
            //是否完成任务
            $v['complete'] = $newer[ $v['label'] ]['complete'];
        }
        $result = array('status'=> true, 'msg'=> '获取成功','data'=> array(
            'temp'   => $daily_strategy,
            'strategy'   => $strategy,
            'member'   => $member,
        ));
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //积分列表
    public function action_ajax_jifen_logs()
    {
        //页码
        $page = intval($this->request_body->content->page);
        //每页数量
        $pagesize = intval($this->request_body->content->pagesize);
        //类型 0- 全部，1-使用，2-获取
        $type = intval($this->request_body->content->type);
        $obj = DB::select()->from('member_jifen_log')->where('memberid', '=', $this->_mid);
        if ($type > 0)
        {
            $obj->where('type', '=', $type);
        }

        //积分列表
        $list = $obj->limit($pagesize)->offset(($page - 1) * $pagesize)->order_by('addtime', 'desc')->execute()->as_array();
        foreach ($list as &$v)
        {
            //时间
            $v['addtime'] = date('Y-m-d H:i', $v['addtime']);
        }
        $this->result['data']['list'] = $list;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * @function 兑换列表
     * @param $param
     * @return mixed
     */
    public function action_query($param)
    {
        $row  = intval($this->request_body->content->row);//每页数量
        $p = intval($this->request_body->content->p);//页码
        $attrid = Common::remove_xss($this->request_body->content->attrid);//属性id
        $flag = Common::remove_xss($this->request_body->content->flag);//标识：order 正常顺序，attr 按属性查询
        switch ($flag)
        {
            case 'attr':
                $list = self::get_integral_by_attrid(($p - 1) * $row, $row, $attrid);
                break;
            case 'order':
                $list = self::get_integral_by_order(($p - 1) * $row, $row);
                break;
        }

        foreach( $list as & $item ){
            $item['litpic'] = Common::img($item['litpic']);
        }

        $result = array(
            'status'    => true,
            'msg'    => '获取成功',
            'data'    => array(
                'list'=> self::_format_data($list)
            )
        );
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //检测邮箱是否注册
    public function action_ajax_check_email()
    {
        $account = Common::remove_xss($this->request_body->content->email);
        $account_info = $this->get_bind_account_info($account);

        $cur_member = Model_Member::get_member_byid($this->_mid);
        $flag = 'false';
        if($account_info['type']==0)
        {
            $flag = 'true';
        }
        else if($account_info['type']==2)
        {
            $binded = $account_info['binded'];
            $cur_binded = DB::select('from')->from('member_third')->where('mid','=',$cur_member['mid'])->execute()->get('from');
            if(empty($cur_member['mobile']) && empty($cur_member['email']) && (empty($binded) || !in_array($cur_binded,$binded)))
            {
                $flag = 'true';
            }
        }
        $result = array(
            'status'    => true,
            'msg'    => '获取成功',
            'data'    => array('flag'=> $flag)
        );
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 发送邮件验证码
     */
    public function action_ajax_send_email_code()
    {
        $email = Common::remove_xss($this->request_body->content->email);
        $code = rand(1000, 9999);//验证码
        if (empty($email)) {
            echo json_encode(array('status' => true, 'msg' => '邮箱不能为空'));
            exit;
        }
        $title = $GLOBALS['cfg_webname'] . '邮箱验证码';
        $content = '邮件验证码' . $code;
        //发送验证码
        $flag = json_decode(St_EmailService::send_email($email, $title, $content));

        if ($flag)//发送成功
        {
            //缓存验证码
            Model_Api_Standard_Pub::cache('set', 'emailcode_' . md5($email), $code);
            $this->result['msg'] = '发送邮箱验证码成功';
        }
        else {
            $this->result['status'] = false;
            $this->result['msg'] = '发送邮箱验证码成功';
        }

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 绑定邮箱保存
     */
    public function action_ajax_email_save()
    {
        //短信验证码
        $email = Common::remove_xss($this->request_body->content->email);//邮箱
        $msg_code = Common::remove_xss($this->request_body->content->checkcode);//验证码
        if (Model_Api_Standard_Pub::cache('get', 'emailcode_' . md5($email)) != $msg_code) {
            $this->result['status'] = false;
            $this->result['msg'] = '验证码错误';
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        $data = array(
            'email' => $email
        );
        $is_bundle = false; //是否绑定
        $mid = $this->_mid;
        $mobile_member = DB::select()->from('member')->where('email', '=', $data['email'])->and_where('mid', '!=', $mid)->execute()->current();
        if (!$mobile_member) {
            $member_info = Model_Member::get_member_byid($mid);
            $old_email = $member_info['email'];
            $old_mobile = $member_info['mobile'];
            if(empty($old_email) && empty($old_mobile) && empty($member_info['pwd']))
            {
                $data['pwd'] = md5($email);
            }
            $flag = DB::update('member')->set($data)->where('mid', '=', $mid)->execute();
            if ($flag) {
                if (empty($old_email)) {
                    $jifen = Model_Jifen::reward_jifen('sys_member_bind_email', $mid);
                    if (!empty($jifen)) {
                        St_Product::add_jifen_log($mid, '绑定邮箱送积分' . $jifen, $jifen, 2);
                    }
                }
                if(!empty($data['pwd']))
                {
                    St_EmailService::send_member_email($email,NoticeCommon::MEMBER_THIRD_BIND_NEW_MSGTAG,$email,"");
                }
                $is_bundle = true;
            }
        }
        else
        {
            $account_info = $this->get_bind_account_info($data['email']);
            $cur_member = Model_Member::get_member_byid($this->_mid);
            //当当前登录用户为第三方登录账户， 且未绑定手机和邮箱时，才可以绑定已存在的账号
            if($account_info['type']==2)
            {
                $binded = $account_info['binded'];
                $cur_binded = DB::select('from')->from('member_third')->where('mid','=',$cur_member['mid'])->execute()->get('from');
                if(empty($cur_member['mobile']) && empty($cur_member['email']) && (empty($binded) || !in_array($cur_binded,$binded)))
                {
                    DB::update('member_third')->set(array('mid'=>$account_info['member']['mid'],'last_mid'=>$this->_mid))->where('mid','=',$this->_mid)->execute();
                }
                Model_Member::login($account_info['member']['email'],$account_info['member']['pwd'],true);
                Model_Member::write_session($account_info['member']);
                $is_bundle = true;
            }
        }
        if( $is_bundle ){
            $this->result['msg'] = '邮箱绑定成功';
        }else{
            $this->result['status'] = false;
            $this->result['msg'] = '邮箱已经注册';
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 积分抽奖数据
     *
     * @return void
     */
    public function action_award()
    {
        //抽奖活动信息
        $info = DB::select()->from('integral_award')->where('is_hidden', '=', 0)->and_where('status', '=', 1)->order_by('id', 'desc')->limit(1);
        $info = $info->execute()->current();
        //奖品套餐
        $suit = DB::select()->from('integral_award_suit')->where('award_id', '=', $info['id'])->order_by('index', 'asc')->execute()->as_array();
        //整合抽奖数据
//        $data = array();
//        $index = array(0, 1, 2, 3, 9, 4, 8, 7, 6, 5);
//        foreach ($index as $v)
//        {
//            foreach ($suit as $s)
//            {
//                if ($s['index'] == ($v + 1))
//                {
//                    $s['index'] -= 1;
//                    $s['litpic'] = Common::img($s['litpic']);
//                    array_push($data, $s);
//                }
//
//            }
//        }

        foreach ($suit as & $v)
        {
            $v['litpic'] = Common::img($v['litpic']);
        }
        //中奖纪录
        $winner = DB::select()->from('integral_winner')->where('award_id', '=', $info['id'])
            ->and_where('product_name', 'not like', '%谢谢%')
//
            ->limit(12)->execute()->as_array();
//        $sql = "select * from sline_integral_winner where award_id={$info['id']} and product_name not like '%谢谢%' limit 12";
//        $winner = DB::query(1,$sql)->execute()->as_array();
        $this->result['data'] = array(
            'info'  => $info,
            'suit'  => $suit,
            'winner'  => $winner,
        );
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    //抽奖前检测
    public function action_ajax_right()
    {
        $msg = array(
            0 => '抽奖已结束',
            1 => '很遗憾，您的可用积分不足，无法参与抽奖'
        );
        $this->result['status'] = false;
        $this->result['msg'] = $msg[0];
        //检测抽奖活动id
        $id = intval($this->request_body->content->no);
        if ($id)
        {
            //用户id
            $member = Model_Member::get_member_byid($this->_mid);
            $award = DB::select()->from('integral_award')->where('id', '=', $id)->and_where('is_hidden', '=', 0)->execute()->current();
            if ($award && $award['status'] != 0)
            {
                //用户积分不足
                if ($member['jifen'] < $award['need_jifen'])
                {
                    $this->result['status'] = false;
                    $this->result['msg'] = $msg[1];
                }else{
                    $this->result['status'] = true;
                    $this->result['msg'] = '';
                }
            }
        }

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 抽奖
     *
     * @return void
     */
    public function action_ajax_luck()
    {
        $msg = array(
            0 => '抽奖已结束',
            1 => '很遗憾，您的可用积分不足，无法参与抽奖'
        );
        $this->result['status'] = false;
        $this->result['msg'] = $msg[0];
        //检测抽奖活动id
        $id = intval($this->request_body->content->no);
        if ($id)
        {
            //用户信息
            $member = Model_Member::get_member_byid($this->_mid);
            $award = DB::select()->from('integral_award')->where('id', '=', $id)->and_where('is_hidden', '=', 0)->execute()->current();
            if ($award && $award['status'] == 1)
            {
                if ($member['jifen'] < $award['need_jifen'])
                {
                    //积分不足
                    $this->result['msg'] = $msg[1];
                }
                else
                {
                    try
                    {
                        //扣除用户积分
                        $jifen = $award['need_jifen'];
                        DB::update('member')->set(array('jifen' => DB::expr("jifen-{$jifen}")))->where('mid', '=', $this->_mid)->execute();
                        St_Product::add_jifen_log($this->_mid, "参与第{$id}期积分抽奖，使用{$jifen}积分", $jifen, 1);
                        //抽奖处理
                        $award = $this->_isLuck($id);
                        //减少数量
                        DB::update('integral_award_suit')->set(array('number'=>DB::expr('number-1')))->where('id','=',$award['id'])->execute();
                        //写入中奖记录
                        $log = array(
                            'member_id' => $this->_mid,
                            'member_nickname' => $member['nickname'],
                            'product_name' => $award['product_name'],
                            'use_jifen' => $jifen,
                            'award_id' => $award['award_id'],
                            'suit_id' => $award['id'],
                            'addtime' => time()
                        );
                        if ($award['award_type_id'] == 1)
                        {
                            $log['link_name'] = $member['nickname'];
                            $log['link_tel'] = $member['mobile'];
                        }
                        if ($award['award_type_id'] == 2)
                        {
                            $log['link_name'] = '无';
                        }
                        list($winnerLogId) = DB::insert('integral_winner', array_keys($log))->values(array_values($log))->execute();
                        //中奖类型为积分
                        if ($award['award_type_id'] == 1 && preg_match('~ig_(\d+)~', $award['value'], $match))
                        {
                            $obj = DB::select()->from('jifen')->where('id', '=', $match[1])->execute()->current();
                            $jifen = Model_Jifen::reward_jifen($obj['label'], $this->_mid);
                            if ($jifen)
                            {
                                $content = "参与第{$id}期积分抽奖，中奖{$jifen}积分";
                                St_Product::add_jifen_log($this->_mid, $content, $jifen, 2);
                            }
                        }
                        //输入信息
                        $this->result['status'] = true;
                        $this->result['msg'] = '操作成功';
                        $this->result['data'] = array('luckNumber' => $award['index'], 'logId' => $winnerLogId, 'title' => $award['product_name'], 'type' => $award['award_type_id']);
                    } catch (Exception $e)
                    {
                        $this->result['msg'] = $msg[1];
                    }
                }
            }
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * @function 保存中奖人联系信息
     */
    public function action_ajax_save_info()
    {
        //抽奖记录id
        $id = intval($this->request_body->content->id);
        $data = array(
            'link_name' => Common::remove_xss($this->request_body->content->link_name),//联系人姓名
            'link_tel' => Common::remove_xss($this->request_body->content->link_tel)//联系人手机号
        );
        if( !$data['link_name'] || !$data['link_tel'] ){
            $this->result['status'] = false;
            $this->result['msg'] = '请输入联系人信息';
        }else{
            DB::update('integral_winner')->set($data)->where('id', '=', $id)->execute();
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 我的中奖记录
     */
    public function  action_record()
    {
        //我的记录列表
        $myRecode = DB::select()->from('integral_winner')->where('member_id', '=', $this->_mid)
            ->and_where('product_name', 'not like', '%谢谢%')
            ->order_by('addtime', 'desc');
        $myRecode = $myRecode->execute()->as_array();
        foreach ($myRecode as &$v)
        {
            $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            //抽奖活动信息
            $info = DB::select('title')->from('integral_award')->where('id', '=', $v['award_id'])->execute()->current();
            $v['title'] = $info['title'];
        }
        $this->result['data']['list'] = $myRecode;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * @function 积分商城热门推荐
     * @return mixed
     */
    public function action_hot_product()
    {   
        //热门推荐
        $limit = intval($this->request_body->content->row);
        $malltype = intval($this->request_body->content->malltype);
        $obj = DB::select()->from('integral')->where('ishidden', '=', 0)->and_where('number', '>', 0);
        if ( isset($malltype) && $malltype )
        {
            $obj->where('mall_type_id', '=', $malltype);
        }
        //积分产品
        $result = $obj->order_by('displayorder', 'asc')->order_by('modtime', 'desc')->limit($limit)->execute() ->as_array();
        foreach ( $result as &$res ){
            $res['litpic'] = Common::img($res['litpic']);
        }
        $this->result['data']['hot'] = self::_format_data($result);

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 积分兑换券
     *
     * @return void
     */
    public function action_coupon_product()
    {
        $page = intval($this->request_body->content->p);//页码
        $row = intval($this->request_body->content->row);//每页 数量
        //判断优惠券应用状态
        $isShow = St_Functions::is_normal_app_install('coupon');
        if( $isShow ){
            //查询兑换券产品
            $out = Model_Coupon::search_result(array(), $page, $row,null,null,2);
            $list = $out['list'];
            foreach($list as &$l)
            {
                $l['litpic']  = Common::img('/uploads/integral.jpg');
                $l['title'] = $l['name'];
            }
        }
        $this->result['data']['coupon'] = $list;
        $this->result['data']['coupon_show'] = $isShow;

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * @function 获取产品属性分类
     * @param $param
     * @return mixed
     */
    public function action_attr($param)
    {
        $attr = DB::select()->from('integral_attr')->where('isopen', '=', 1)->and_where('id', '!=', 1)->order_by(DB::expr('IFNULL(`displayorder` ,9999)'), 'asc')->limit($param['row']);
        $attr = $attr->execute()->as_array();
        $this->result['data']['attr'] = $attr;

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * @function 积分商城产品详情页
     */
    public function action_show()
    {
        $id = intval($this->request_body->content->id);
        $info = Model_Integral::get_integral_info_by_id($id);
        if ( !$info )
        {
           $this->result['status'] = false;
           $this->result['msg'] = '产品不存在';
        }else{
            foreach ($info['piclist'] as & $item) {
                $item[0] = Common::img($item[0]);
            }
            //用户已兑换数量
            $info['need_jifen'] = intval($info['need_jifen']);
            $info['need_address'] = intval($info['need_address']);
            $info['number'] = intval($info['number']);
            $info['member_max_number'] = intval($info['member_max_number']);
            $info['get_num'] = intval(DB::query(1, "select sum(`dingnum`) as num from `sline_member_order` where `typeid`=107 and `productaid`=$id and memberid=".$this->_mid)->execute()->get("num"));
            $this->result['data']['detail'] = $info;
        }

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 保存收货地址
     *
     * @return void
     */
    public function action_address_save()
    {
        $_POST = array(
            'receiver'  => Common::remove_xss($this->request_body->content->receiver),//收货地址用户名
            'phone'  => Common::remove_xss($this->request_body->content->phone),//电话号码
            'postcode'  => Common::remove_xss($this->request_body->content->postcode),//邮政编码
            'province'  => Common::remove_xss($this->request_body->content->province),//省
            'city'  => Common::remove_xss($this->request_body->content->city),//市
            'address'  => Common::remove_xss($this->request_body->content->address),//区
            'is_default'  => intval($this->request_body->content->is_default),//是否默认
            'id'  => intval($this->request_body->content->id),//地址id
        );
        if (empty($_POST['id']))
        {
            $_POST['memberid'] = $this->_mid;
            list($id, $rows) = DB::insert('member_address', array_keys($_POST))
                                 ->values(array_values($_POST))
                                 ->execute();
            if ($rows > 0)
            {
                //更新默认
                if ($_POST['is_default'] == 1)
                {
                    DB::update('member_address')
                      ->set(array('is_default' => 0))
                      ->where('id', '!=', $id)
                      ->execute();
                }
            }
            else
            {
                $this->result['msg'] = __('error_add');
                $this->result['status'] = false;
            }
        }
        else
        {
            $id = $_POST['id'];
            unset($_POST['id']);
            $rows = DB::update('member_address')
                      ->set($_POST)
                      ->where("id={$id} and memberid={$this->_mid}")
                      ->execute();
            if ($rows > 0)
            {
                //更新默认
                if ($_POST['is_default'] == 1)
                {
                    DB::update('member_address')
                      ->set(array('is_default' => 0))
                      ->where('id', '!=', $id)
                      ->execute();
                }
            }
            else
            {
                $this->result['msg'] = __('error_edit');
                $this->result['status'] = false;
            }
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 默认地址
     */
    public function action_default_address()
    {
        //地址列表
        $addresses = Model_Member_Address::get_address($this->_mid);
        $default_address = array();
        $has_default = false;
        if (! empty($addresses))
        {
            foreach ($addresses as $address)
            {
                if ($address['is_default'] == 1)
                {
                    $default_address = $address;
                    $has_default = true;
                    break;
                }
            }
            $default_address = ! $has_default ? $addresses[0] : $default_address;
            //是否有默认值 true：有，false：无
            $this->result['data']['empty'] = true;
        }else{
            $this->result['data']['empty'] = false;
        }
        //默认地址数据
        $this->result['data']['default'] = $default_address;

        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 地址列表
     *
     * @return void
     */
    public function action_address_more()
    {
        $page = intval($this->request_body->content->page);//页码
        $page = $page < 1 ? 1 : $page;
        $pageSize = 10;//每页数量
        $list = DB::select()->from('member_address')->where('memberid', '=', $this->_mid)->limit($pageSize)->offset(($page - 1) * $pageSize)->execute()->as_array();
        $this->result['data']['list'] = $list;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 兑换产品
     */
    public function action_exchange()
    {
        $id = intval($this->request_body->content->id);
        $book_num = intval($this->request_body->content->booknum);//预订数量
        $linkman = Common::remove_xss($this->request_body->content->linkman);//联系人姓名
        $linktel = Common::remove_xss($this->request_body->content->linktel);//联系人手机号
        $linkemail = Common::remove_xss($this->request_body->content->linkemail);//联系人邮箱
        $remark = Common::remove_xss($this->request_body->content->remark);//备注
        $receive_address_id = Common::remove_xss($this->request_body->content->receive_address_id);//收货地址id
        if ($book_num < 1)
        {
            $this->result['msg'] = '提交无效数据';
            $this->result['status'] = false;
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        //产品信息
        $info = Model_Integral::get_integral_info_by_id($id);
        //用户已兑换数量
        $get_num = DB::query(1, "select sum(`dingnum`) as num from `sline_member_order` where `typeid`=107 and `productaid`=$id and memberid=".$this->_mid)->execute()->get("num");
        if ($book_num + $get_num > $info['member_max_number'])
        {
            //兑换数量+已兑换数量>单个用户最大订购量
            $this->result['msg'] = '预订数量超过单个用户最大订购量';
            $this->result['status'] = false;
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        //判断收货地址
        if ( $info['need_address'] && !$receive_address_id ){
            $this->result['msg'] = '请传入收货地址';
            $this->result['status'] = false;
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        //用户信息
        $member = Model_Member::get_member_byid($this->_mid);
        if ($member['jifen'] < $book_num * $info['need_jifen'])
        {
            //积分不足
            $this->result['msg'] = '积分不足';
            $this->result['status'] = false;
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        //下订单
        try
        {
            //减库存
            DB::update('integral')
              ->set(array('number' => DB::expr("number-{$book_num}")))
              ->where('id', '=', intval($id))
              ->execute();
            try
            {
                //下单成功
                $_POST['remark']['book'] = htmlentities($_POST['remark']['book']);
                $data = array(
                    'webid'         => 0,
                    'price'         => 0,
                    'status'        => 5,
                    'usejifen'      => 1,
                    'paytype'       => 1,
                    'ispinlun'      => 1,
                    'paytime'       => time(),
                    'addtime'       => time(),
                    'paysource'     => '积分兑换',
                    'ordersn'       => Product::get_ordersn(107),
                    'needjifen'     => $book_num * $info['need_jifen'],
                    'litpic'        => $info['litpic'],
                    'typeid'        => 107,
                    'memberid'      => $this->_mid,
                    'productaid'    => $info['id'],
                    'productautoid' => $info['id'],
                    'productname'   => $info['title'],
                    'dingnum'       => $book_num,
                    'remark'        => serialize(['book'=>$remark]),
                    'linkman'       => htmlentities($linkman),
                    'linktel'       => htmlentities($linktel),
                    'linkemail'     => htmlentities($linkemail),
                );
                if ($receive_address_id != 0)
                {
                    //检查该用户地址是否可用
                    if (Model_Member_Address::check_address_id($this->_mid, $receive_address_id))
                    {
                        $data['receiver_address_id'] = intval($receive_address_id);
                    }
                }

                list($autoid, $row) = DB::insert('member_order', array_keys($data))
                                        ->values(array_values($data))
                                        ->execute();
                if (! $row)
                {
                    throw  new Exception('用户下单失败');
                }
                //扣除积分并写入日志
                DB::update('member')
                  ->set(array('jifen' => DB::expr('jifen-' . $data['needjifen'])))
                  ->where('mid', '=', $this->_mid)
                  ->execute();
                $content = "兑换产品<{$data['productname']}>使用{$data['needjifen']}积分";
                St_Product::add_jifen_log($this->_mid, $content, $data['needjifen'], 1);
                $rtn['status'] = 1;
                $rtn['msg'] = '兑换成功！';
                $rtn['data'] = array(
                    'ordersn'   => $data['ordersn'],
                    'title'     => vsprintf('<a href="/integral/show_%d.html">%s</a>', array(
                        $info['id'],
                        $info['title'],
                    )),
                    'needjifen' => vsprintf('<em>%d积分</em>', $data['needjifen']),
                );

            }
            catch (Exception $e)
            {
                //下单失败
                DB::update('integral')
                  ->set(array('number' => DB::expr("number+{$book_num}")))
                  ->where('id', '=', $info['id'])
                  ->execute();
                $this->result['msg'] = '服务器繁忙，请稍后再试';
                $this->result['status'] = false;

            }

        }
        catch (Exception $e)
        {
            $this->result['msg'] = '产品库存不足';
            $this->result['status'] = false;
        }
        $this->result['data']['orderid'] = isset($autoid) && $autoid ? $autoid : 0;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 订单详细
     */
    public function action_order_show()
    {
        $id = intval($this->request_body->content->id);
        $info = Model_Member_Order::get_order_detail($id, $this->_mid);
        if ($info['receiver_address_id'])
        {
            $bool = Model_Member_Address::check_address_id($this->_mid, $info['receiver_address_id']);
            //收货地址信息
            $address = $bool ? Model_Member_Address::get_address_info($info['receiver_address_id']) : array();
            $info['address_info'] = $address;
        }
        //产品积分单价
        $info['single_jifen'] = intval(intval($info['needjifen']) / intval($info['dingnum']));
        //图片地址
        $info['litpic'] = Common::img($info['litpic']);
        //备注
        $info['remark'] = unserialize($info['remark'])['book'];
        $this->result['data']['info'] = $info;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 积分兑换券详情
     */
    public function action_coupon_exchange_detail()
    {
        //积分兑换券id
        $cid = intval($this->request_body->content->cid);
        if( $cid ){
            $info = Model_Coupon::get_integral_info($cid,  $this->_mid);
        }
        //图片地址
        $info['litpic'] = $GLOBALS['cfg_basehost'].'/plugins/coupon/public/mobile/images/integral_show.jpg';

        $sql = "select count(*) as num from sline_member_coupon WHERE cid=$cid and mid=".$this->_mid;
        $info['get_num'] = intval(DB::query(1,$sql)->execute()->get('num'));
        $info['need_jifen'] = intval($info['needjifen']);
        if( $info['type'] == 1 ){
            $info['amount'] = $info['amount'] / 10;
        }
        if ($info['typeid']==0)
        {
            $info['typename'] = '';
        }
        else
        {
            $info['typename'] = self::get_coupon_type($info['id'],$info);
        }
        $this->result['data'] = $info;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 积分商城领取优惠券
     */
    public function action_get_coupon_from_integral()
    {
        $userInfo  = Model_Member::get_member_info($this->_mid);
        $cid = intval($this->request_body->content->cid);
        $flag = Model_Coupon::check_receive_status($cid);
        switch($flag['status'])
        {
            case 1:
                $couponinfo = DB::select('needjifen','name')->from('coupon')->where("id=$cid and kindid=2")->execute()->current();
                if($userInfo['jifen']<$couponinfo['needjifen'])
                {
                    $this->result['msg'] = '领取失败,您的积分不足以兑换该优惠券';
                    $this->result['status'] = false;
                }
                else
                {
                    $result =  Model_Coupon::get_coupon($cid,$userInfo['mid']);
                    if($result)
                    {
                        try
                        {
                            //扣除积分并写入日志
                            DB::update('member')->set(array('jifen'=>DB::expr('jifen-'.$couponinfo['needjifen'])))->where('mid','=',$userInfo['mid'])->execute();
                            $content = "兑换优惠券<{$couponinfo['name']}>使用{$couponinfo['needjifen']}积分";
                            St_Product::add_jifen_log($userInfo['mid'], $content,$couponinfo['needjifen'], 1);
                        }
                        catch(Exception $e)
                        {
                            //删除优惠券
                            DB::delete('coupon')->where("id={$result[0]} and cid=$cid")->execute();
                            $this->result['msg'] = '领取失败';
                            $this->result['status'] = false;
                        }
                    }

                }
                break;
            case 2:
                $this->result['msg'] = '领取失败,该优惠券已经领完';
                $this->result['status'] = false;
                break;
            case 3:
                $this->result['msg'] = '领取失败,您已经领取过该优惠券';
                $this->result['status'] = false;
                break;
            case 4:
                $this->result['msg'] = '领取失败,您的会员等级不满足条件';
                $this->result['status'] = false;
                break;
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }
    
    /*************************私有方法************************* */

    /**@function 获取优惠券的适用类型
     * @param $cid
     * @return string
     */
    private static function get_coupon_type($cid,$info)
    {
        if($info['typeid']==9999)
        {
            $sql = "select distinct b.modulename from sline_coupon_pro as a  LEFT join sline_model as b on a.typeid=b.id WHERE a.cid=$cid";
            $result = DB::query(1, $sql)->execute()->as_array();
            $typename = '';
            foreach ($result as $r)
            {
                $typename .= $r['modulename'] . ',';
            }
            $typename = rtrim($typename, ',');
        }
        else
        {

            $modules = $info['modules'];
            $modules = DB::select('modulename')->from('model')->where("id in ({$modules})")->execute()->as_array();
            $typename = '';
            foreach ($modules as $r)
            {
                $typename .= $r['modulename'] . ',';
            }
            $typename = rtrim($typename, ',');
        }

        return Common::cutstr_html($typename,18);
    }

    /**
     * @function 获取将要绑定的手机号或邮箱信息, $type, 0表示新手机号或邮箱， 1表示与登录的手机号一样，2，表示手机号存在
     * @param $account
     */
    private function get_bind_account_info($account)
    {

        $info = array('type'=>0,'field'=>'email');
        $field='mobile';
        if (strpos($account, '@'))
        {
            // $where = "email='{$loginname}'";
            $field='email';
            $info['field'] = $field;
        }
        $result = DB::select()->from('member')->where($field,'=',$account)->execute()->current();
        $info['member'] = $result;
        if(empty($result))
        {
           $info['type'] = 0;
        }
        else if($result['mid']==$this->_mid)
        {
            $info['type'] = 1;
        }
        else
        {
            $info['type'] = 2;
        }

        $bind_third_arr = DB::select()->from('member_third')->where('mid','=',$result['mid'])->execute()->as_array();
        $binded = array();
        foreach($bind_third_arr as $row)
        {
            $binded[] = $row['from'];
        }
        $info['binded'] = $binded;
        return $info;
    }

    /**
     * @function 通过类型获取数据
     * @param $offset
     * @param $row
     * @param $attrid
     * @return mixed
     */
    private static function get_integral_by_attrid($offset, $row, $attrid)
    {
        $rows = DB::select()
                  ->from('integral')
                  ->where('mall_type_id', '=', $attrid)
                  ->and_where('ishidden', '=', 0)
                  ->and_where('number', '>', 0)
                  ->order_by('displayorder', 'asc')
                  ->order_by('modtime', 'desc')
                  ->offset($offset)
                  ->limit($row)
                  ->execute()
                  ->as_array();

        return $rows;
    }

    /**
     * @function 按顺便读取数据
     * @param $offset
     * @param $row
     * @return mixed
     */
    private static function get_integral_by_order($offset, $row)
    {
        $rows = DB::select()
                  ->from('integral')
                  ->where('ishidden', '=', 0)
                  ->and_where('number', '>', 0)
                  ->order_by('displayorder', 'asc')
                  ->order_by('modtime', 'desc')
                  ->offset($offset)
                  ->limit($row)
                  ->execute()
                  ->as_array();

        return $rows;
    }

    /**
     * @function 积分商城产品格式化数据
     * @param $data
     * @return mixed
     */
    private static function _format_data($data)
    {
        foreach ($data as $k => &$v)
        {
            $v['url'] = Common::get_web_url($v['webid']) . "/integral/show_{$v['id']}.html";
        }
        return $data;
    }

    /**
     * @function 获取奖品
     * @return mixed
     */
    private function _isLuck($id)
    {
        $suit = DB::select()->from('integral_award_suit')->where('award_id', '=', $id)->execute()->as_array();
        //重新计算概率
        $total = 0;
        foreach ($suit as &$v)
        {
            if ($v['number']>0)
            {
                $total += $v['percentage'];
            }
            else
            {
                $v['percentage'] = 0;
            }
        }
        if ($total)
        {
            foreach ($suit as &$v)
            {
                $v['percentage'] = ceil($v['percentage'] / $total * 100);
            }
        }
        return $this->_get_award($suit);
    }

    private function _get_award($data)
    {
        $arr = array();
        usort($data, array($this, '_sort'));
        foreach ($data as $key => $val)
        {
            $arr[$key + 1] = $val['percentage'];
        }
        $rid = $this->_get_rand($arr);
        $award = $data[$rid - 1];
        return $award;
    }

    private function _sort($obj, $nextObj)
    {
        return $obj['percentage'] > $nextObj['percentage'] ? -1 : 1;
    }

    /**
     * @function 抽奖算法
     * @param $proArr
     * @return int|string
     */
    private function _get_rand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur)
        {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur)
            {
                $result = $key;
                break;
            }
            else
            {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
}